package com.gcloud.mesh.dcs.chain.huawei;

import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import com.gcloud.mesh.dcs.dao.AppInstanceDao;
import com.gcloud.mesh.dcs.entity.AppInstanceEntity;
import com.gcloud.mesh.dcs.service.AppService;
import com.gcloud.mesh.header.param.HuaweiMigrationParam;
import com.google.api.client.util.Lists;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.GlobalCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.ecs.v2.EcsClient;
import com.huaweicloud.sdk.ecs.v2.model.UpdateServerOption;
import com.huaweicloud.sdk.ecs.v2.model.UpdateServerRequest;
import com.huaweicloud.sdk.ecs.v2.model.UpdateServerRequestBody;
import com.huaweicloud.sdk.ecs.v2.model.UpdateServerResponse;
import com.huaweicloud.sdk.ecs.v2.region.EcsRegion;
import com.huaweicloud.sdk.sms.v3.SmsClient;
import com.huaweicloud.sdk.sms.v3.model.ShowTaskRequest;
import com.huaweicloud.sdk.sms.v3.model.ShowTaskResponse;
import com.huaweicloud.sdk.sms.v3.region.SmsRegion;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.log.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

//@Component
@Slf4j
public class UpdateServer_5 extends AbstractHuaweiMigrationStep{

//    @Autowired
//    private AppInstanceDao appInstanceDao;
	@Autowired
	private AppService appService;
    
    

    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        HuaweiMigrationParam huaweiMigrationParam = JSONObject.toJavaObject(jsonObject,HuaweiMigrationParam.class);
        String taskId = jsonObject.getString("taskId");
        String targetRegionId = huaweiMigrationParam.getDestRegionId();
        String appName = huaweiMigrationParam.getVmName();
        String accessKeyId = huaweiMigrationParam.getAccessKey();
        String accessSecret = huaweiMigrationParam.getSecretKey();
        ShowTaskResponse res = showTask(accessKeyId, accessSecret,taskId);
//            appInstanceEntity.setName(res.getTargetServer().getHostname());
        List<String> list = Lists.newArrayList();
        list.add("instanceId");
        appService.updateInstanceDBInfo(schedulerJobId, huaweiMigrationParam.getVmId(), res.getTargetServer().getVmId());
        updateServer(accessKeyId, accessSecret, res.getTargetServer().getVmId(), appName, targetRegionId);
        filterChain.doExec(schedulerJobId,jsonObject.toString(),filterChain,stepChain);
    }

    @Override
    public String chainName(String attach) {
        return "修改目标服务器主机名";
    }

    @Override
    public int getOrder() {
        return 5;
    }


    public UpdateServerResponse updateServer(String ak, String sk, String appid, String name, String regionId) {
        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        config.withIgnoreSSLVerification(true);
        EcsClient client = EcsClient.newBuilder()
                .withHttpConfig(config)
                .withCredential(auth)
                .withRegion(EcsRegion.valueOf(regionId))
                .build();
        UpdateServerRequest request = new UpdateServerRequest();
        request.withServerId(appid);
        UpdateServerRequestBody body = new UpdateServerRequestBody();
        UpdateServerOption serverbody = new UpdateServerOption();
        serverbody.withName(name)
                .withHostname(name);
        body.withServer(serverbody);
        request.withBody(body);
        UpdateServerResponse response =  null;
        try {
            response = client.updateServer(request);
        } catch (ConnectionException e) {
            Log.error("修改主机名失败",e);
        } catch (RequestTimeoutException e) {
            Log.error("修改主机名失败",e);
        } catch (ServiceResponseException e) {
            Log.error("修改主机名失败",e);

        }
        return response;
    }


    public ShowTaskResponse showTask(String ak, String sk, String taskId) {
        if(StringUtils.isBlank(ak)) {
            ak = "8QVISVT4XJHUNMIEPZBQ";
        }
        if(StringUtils.isBlank(sk)) {
            sk = "GingsSlHInSkQ3x47jMSEjFT0uumSJgplZs926Cw";
        }
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        config.withIgnoreSSLVerification(true);
        ShowTaskResponse response = null;
        ICredential auth = new GlobalCredentials()
                .withAk(ak)
                .withSk(sk);

        SmsClient client = SmsClient.newBuilder()
                .withCredential(auth)
                .withHttpConfig(config)
                .withRegion(SmsRegion.valueOf("ap-southeast-1"))
                .build();
        ShowTaskRequest request = new ShowTaskRequest();
        request.withTaskId(taskId);
        try {
            response = client.showTask(request);
            response.getState();
        } catch (ConnectionException e) {
            log.error("迁移获取任务详情失败："+ e);
//            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            log.error("迁移获取任务详情失败："+ e);
//            e.printStackTrace();
        } catch (ServiceResponseException e) {
            log.error("迁移获取任务想请失败："+ e);
//            e.printStackTrace();
//            System.out.println(e.getHttpStatusCode());
//            System.out.println(e.getErrorCode());
//            System.out.println(e.getErrorMsg());
        }
        return response;
    }
}
